package sany.iec.service;

import lombok.extern.slf4j.Slf4j;
import org.openmuc.j60870.ASdu;
import org.openmuc.j60870.CauseOfTransmission;
import org.openmuc.j60870.Connection;
import org.openmuc.j60870.ConnectionEventListener;
import org.openmuc.j60870.ie.IeQualifierOfInterrogation;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @Author : 托马斯
 * @Date : 2025/6/27 11:11
 * @Description :
 */
@Slf4j
@Service
public class IEC104Listener implements ConnectionEventListener {
    @Override
    public void newASdu(Connection connection, ASdu aSdu) {
        log.info("子站自动触发：{}", aSdu.toString());
    }

    @Override
    public void connectionClosed(Connection connection, IOException e) {
        log.warn("连接断开：{}", e.getMessage(), e);
    }

    @Override
    public void dataTransferStateChanged(Connection connection, boolean b) {
        if (b) {
            log.warn("数据传输停止~~~");
            return;
        }
        log.info("数据传输：启动，准备发送测试命令...");
        // ... 比如发送 总召
        callC_IC_NA_1(connection, 1);
    }

    /**
     * 总召
     */
    private void callC_IC_NA_1(Connection connection, int commonAddress) {
        try {
            connection.interrogation(
                    commonAddress, // 公共地址
                    CauseOfTransmission.ACTIVATION, // 6
                    new IeQualifierOfInterrogation(20) // 召唤限定词，默认20，表示全站总召唤
            );
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
